package com.xiaoc.bulldozer.common.util;

import org.apache.poi.hssf.usermodel.*;

import java.util.List;
import java.util.Map;

public class ReportServiceImpl<T> {

    public void exportSellExcel(List<T> objs, HSSFWorkbook workbook, String[] headers, HSSFSheet sheet,Map<String,String> map) {

        //设置头
        int rowNum =0;
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        HSSFRow row = sheet.createRow(0);
        //设置表头
        setHeaders(sheet,style,font,headers,row,map);

        HSSFCellStyle style_1 = workbook.createCellStyle();
        HSSFFont font_1=workbook.createFont();
        Integer size = headers.length;
        for(T obj:objs){
            rowNum++;
            createRow(obj,sheet,rowNum,size,headers,style_1,font_1);
        }
    }

    public void setHeaders(HSSFSheet sheet,HSSFCellStyle style,HSSFFont font,String[] headers,HSSFRow row,Map<String,String> map){
        Integer length = headers.length;
        row.setHeight((short)400);

        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        font.setFontHeightInPoints((short)10);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //把字体应用到当前的样式
        style.setFont(font);
        style.setWrapText(true);

        for(int i=0;i<length;i++) {
            HSSFCell cell = row.createCell(i);
            String name = map.get(headers[i]);
            HSSFRichTextString text = new HSSFRichTextString(name);
            sheet.setColumnWidth(i, name.getBytes().length*256);
            cell.setCellValue(text);
            cell.setCellStyle(style);
        }
    }

    public void createRow(T obj, HSSFSheet sheet, Integer rowNum, Integer size, String[] header, HSSFCellStyle style, HSSFFont font){
        try {
            HSSFRow rown = sheet.createRow(rowNum);
            style.setWrapText(true);
            font.setFontHeightInPoints((short)10);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style.setFont(font);
            rown.setHeight((short)400);
            String result = "";
            for (int i=0;i<size;i++) {
                Object object = ReflexUtil.getGetMethod(obj, header[i]);
                if (object != null ) {
                    result = object.toString();
                } else {
                    result = "";
                }
                rown.createCell(i).setCellValue(result);
                rown.setRowStyle(style);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
